package com.marcocirillo.justweet;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JDialog;
import javax.swing.JOptionPane;

import twitter4j.TwitterException;

public class Controller implements ActionListener {

	private JusTweet jt;
	private View v;
	private LoginWindow lw;
	//private GUI gui;
	
	public Controller(JusTweet jt, View v)
	{
		this.jt = jt;
		this.v = v;
	}
	
	public Controller(JusTweet jt, LoginWindow lw)
	{
		this.jt = jt;
		this.lw = lw;
	}
	@Override
	public void actionPerformed(ActionEvent e) {

		String s = e.getActionCommand();
		if (s.equals(View.TWEET_TEXT))
		{			
			try 
			{
				jt.updateStatus(v.getTweetText());
			} catch (TwitterException e1) 
			{
				System.out.println(e1.getMessage());
			}
		
			v.clearTweetText();
			try {
				v.setCurrentStatus(jt);
			} catch (TwitterException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} else if (s.equals(LoginWindow.LOGIN_TEXT))
		{
			String username = lw.getUsernameText();
			String password = lw.getPasswordText();
			this.jt = new JusTweet(username, password);
			if (this.jt.isAuthenticated())
			{
				//gui.setJusTweet(this.jt);
				System.out.println("Auth good, saving to JusTweet.ini");
				JusTweet.saveAccount(username, password);
				View v = new View(500, 300, jt);
				v.setVisible(true);
				this.lw.dispose();
			} else
			{  // jt not authenticated, bad user/pass
	    		this.jt = null;
	    		JOptionPane.showMessageDialog(new JDialog(), "Invalid username/password. We will delete JusTweet.ini so you can try again", "Authentification Failed!", JOptionPane.ERROR_MESSAGE);
	    		//settings.delete();
			}
		}

	}

}
